<template>
  <div :class="ns.b()">
    <div :class="ns.e('page-title')">绿色信贷</div>

    <div :class="ns.e('filter-wrapper')">
      <vc-filter :menus="menus"></vc-filter>
      <div :class="ns.e('filters')">
        <div :class="ns.e('source')">
          <span>溯源</span>
          <el-switch v-model="traceSource" size="small" style="--el-switch-on-color: #02C680;" class="mr-2"/>
          <span :class="ns.e('total-num')">
          共计 <sapn style="color: rgba(255, 89, 89, 1)">{{ totalNum }}</sapn> 条
          </span>
        </div>

      </div>
    </div>

    <div :class="ns.e('table-wrapper')">
      <vc-table
        :loading="loading"
        :tableData="tableData"
        :columns="columns"
        :total="totalNum"
        :pageSize="queryData.pageSize"
        v-model:pageNum="queryData.pageNum"
        :defaultSort="{ field: '300211', order: 'desc' }"
        @page-change="handleCurrentChange"
        @sort-change="sortChange"
      />
    </div>

    <indicator-source v-model:show="showActionsheet" :actionData="actionSheetData"></indicator-source>
  </div>
</template>

<script setup lang="tsx">
import { useNamespace } from 'vc/src/use';
import { useScreen } from './useScreen';
import { useTable } from './useTable';
import { getGreenCredit } from '../apis';
import { COMPANY_NAME } from '@/utils';
import indicatorSource from '@/components/indicator-source/index.vue';

const ns = /* hoist-static*/ useNamespace('greenCredit');
defineOptions({ name: ns.b() });

const { queryData, organizationTypeChanged, menus, traceSource } = useScreen();

const { totalNum, tableData, columns } = useTable();
const showActionsheet = ref(false);
const actionSheetData = ref();

const loading = ref(false);
const getData = async () => {
  loading.value = true;
  const res = await getGreenCredit(queryData);
  organizationTypeChanged.value = false;
  loading.value = false;
  const { _columns, _data } = handleRes(res);
  columns.value = [
    ...[
      {
        type: 'seq',
        title: '序号',
        width: 70,
        fixed: 'left',
        align: 'center',
        slots: {
          default: ({ row, rowIndex }) => {
            return rowIndex ? rowIndex + queryData.pageSize * (queryData.pageNum - 1) : '';
          }
        }
      },
      { ...COMPANY_NAME }
    ],
    ..._columns
  ];
  totalNum.value = res.total;
  tableData.value = _data;
};

const isFirstLoad = ref(true);
const isPageChange = ref(false);
watch(
  () => organizationTypeChanged.value,
  (val) => {
    if (val) {
      getData();
    }
  }
);
watch(
  () => queryData,
  (val) => {
    if (isFirstLoad.value) {
      if (val.statisticalPeriod && val.currencyType) {
        isFirstLoad.value = false;
        getData();
      }
    } else {
      if (!isPageChange.value) {
        queryData.pageNum = 1;
      } else {
        isPageChange.value = false;
      }
      getData();
    }
  },
  { deep: true }
);

const handleCurrentChange = (page: number) => {
  queryData.pageNum = page;
  isPageChange.value = true;
};

const sortChange = (event: any) => {
  const { field, order } = event;
  queryData.indicatorFiled = field;
  queryData.indicatorOrder = order;
};

const openSourceDialog = (item, remark) => {
  if (remark || (item.indicatorDisplayValue && traceSource.value)) {
    item.year = item.statisticalPeriod;
    item.value = item.indicatorDisplayValue;
    actionSheetData.value = item;
    showActionsheet.value = true;
  }
};
const openSourceDialogWithoutTraceSource = (item, remark) => {
  if (remark) {
    openSourceDialog(item, remark);
  }
};

const handleRes = (res: any) => {
  let _columns: any[] = [];
  let _units = {
    companyName: '单位'
  };

  let _data: any[] = [];

  if (res.indicators && res.indicators.length) {
    res.indicators.forEach((ind) => {
      _columns.push({
        title: ind.name,
        field: ind.code,
        width: 150,
        align: 'center',
        sortable: true,
        sortBy: ind.code,
        slots: {
          default: ({ row }) => {
            const showRemark = row[ind.code] && row[ind.code] !== '-' && row[ind.code + 'Obj'] && (row[ind.code + 'Obj'].calcIndicatorRemark || row[ind.code + 'Obj'].contentDescription);
            if (traceSource.value && row.companyName !== '单位' && row[ind.code] !== '-' && row[ind.code + 'Obj'].fileUrl) {
              return (
                <a class={showRemark ? 'show-remark' : ''} onClick={() => openSourceDialog(row[ind.code + 'Obj'], showRemark)}>
                  {row[ind.code]}
                </a>
              );
            } else {
              return (
                <span class={showRemark ? 'show-remark' : ''} onClick={() => openSourceDialogWithoutTraceSource(row[ind.code + 'Obj'], showRemark)}>
                  {row[ind.code]}
                </span>
              );
            }
          }
        }
      });
      _units[ind.code] = ind.unit;
    });
  }

  if (res.details && res.details.length) {
    _data = res.details.map((d) => {
      let left = {
        companyId: d?.performanceSecurities?.companyId || '',
        companyName: d?.performanceSecurities?.securitiesName || ''
      };
      let right = {};
      d.indicatorInfo.forEach((indi, i) => {
        if (indi && indi?.indicatorDisplayValue) {
          right[_columns[i].field] = indi?.indicatorDisplayValue;
          right[_columns[i].field + 'Obj'] = indi;
        } else {
          right[_columns[i].field] = '-';
          right[_columns[i].field + 'Obj'] = {};
        }
      });
      return { ...left, ...right };
    });
    _data.unshift(_units);
  }

  return {
    _columns,
    _data
  };
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
